#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
会话状态变更接口
"""

from datetime import datetime
from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_service_state_trans_bp = Blueprint('kf_service_state_trans', __name__)
logger = get_logger(__name__)


@kf_service_state_trans_bp.route('/cgi-bin/kf/service_state/trans', methods=['POST'])
def trans_service_state():
    """变更会话状态 - 带时间窗口的重复检测"""
    try:
        # 获取请求参数
        access_token = request.args.get('access_token')
        
        logger.info("会话状态变更请求")
        
        # 参数验证
        if not access_token:
            logger.warning("缺少access_token参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing access_token parameter"
            }), 400
        
        # 获取请求体
        request_data = request.get_json()
        if not request_data:
            logger.warning("缺少请求体")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing request body"
            }), 400
        
        external_userid = request_data.get('external_userid')
        open_kfid = request_data.get('open_kfid')
        service_state = request_data.get('service_state')
        servicer_userid = request_data.get('servicer_userid', '')
        
        logger.info(f"状态变更 - 用户: {external_userid}, 客服账号: {open_kfid}, 状态: {service_state}")
        
        # 参数验证
        if not external_userid or not open_kfid or service_state is None:
            logger.warning("缺少必要参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing required parameters"
            }), 400
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # 验证访问令牌
        if not data_manager.validate_token(access_token):
            logger.warning("无效的access_token")
            return jsonify({
                "errcode": 40014,
                "errmsg": "invalid access_token"
            }), 400
        
        # 获取当前会话状态（不更新活动时间，仅检查超时）
        current_session = data_manager.get_session(external_userid, open_kfid, update_activity=False)
        current_state = current_session.get('service_state') if current_session else None
        current_time = int(datetime.now().timestamp())
        
        # 检查是否为10秒内的重复状态转移
        if current_session and current_state == service_state:
            last_update_time = current_session.get('update_time', 0)
            time_diff = current_time - last_update_time
            if time_diff <= 10:  # 10秒内的重复状态转移
                logger.warning(f"10秒内重复状态转移 - 当前状态: {current_state}, 目标状态: {service_state}, 时间差: {time_diff}秒")
                return jsonify({
                    "errcode": 95016,
                    "errmsg": "service state transfer not allowed (duplicate within 10 seconds)"
                }), 400
            else:
                logger.info(f"超过10秒的相同状态转移，允许执行 - 时间差: {time_diff}秒")
                # 超过10秒的相同状态转移直接放行，跳过状态流转验证
        else:
            # 状态变更验证（仅对非相同状态的转移进行验证）
            if not _validate_state_transition(current_session, service_state):
                logger.warning(f"不允许的状态变更 - 当前状态: {current_state}, 目标状态: {service_state}")
                return jsonify({
                    "errcode": 95016,
                    "errmsg": "service state transfer not allowed"
                }), 400
        
        # 更新会话状态
        session_data = {
            "external_userid": external_userid,
            "open_kfid": open_kfid,
            "service_state": service_state,
            "servicer_userid": servicer_userid,
            "update_time": int(datetime.now().timestamp())
        }
        
        # 如果是新会话，添加创建时间
        if not current_session:
            session_data["create_time"] = int(datetime.now().timestamp())
        else:
            session_data["create_time"] = current_session.get("create_time")
        
        data_manager.update_session(external_userid, open_kfid, session_data)
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"会话状态变更成功 - 新状态: {service_state}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok"
        })
        
    except Exception as e:
        logger.error(f"会话状态变更失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500


def _validate_state_transition(current_session, target_state):
    """验证状态变更是否允许"""
    if not current_session:
        # 新会话，允许任何状态
        return True
    
    current_state = current_session.get('service_state', 4)
    
    # 状态流转规则
    allowed_transitions = {
        0: [1, 2, 3, 4],  # 未处理 -> 智能助手/待接入/人工接待/结束
        1: [2, 3, 4],     # 智能助手 -> 待接入/人工接待/结束
        2: [3, 4],        # 待接入 -> 人工接待/结束
        3: [4],           # 人工接待 -> 结束
        4: [0, 1, 2, 3]   # 结束 -> 重新开始
    }
    
    return target_state in allowed_transitions.get(current_state, [])
